package com.qfedu.luck.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @program: LuckStudy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-02-24 14:24
 */
public class JdbcUtil {
    private static DruidDataSource druidDataSource;
    private static Connection connection;
    static {
        druidDataSource=new DruidDataSource();
        druidDataSource.setUsername("root");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/db_lucky?serverTimezone=Asia/Shanghai");
        druidDataSource.setPassword("root");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        try {
            connection=druidDataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //执行非查询语句
    public static int execu(String sql, Map<Integer,Object> map){
        try {
            //预处理对象 防止SQL注入
            PreparedStatement ps=connection.prepareStatement(sql);
            for(Integer k:map.keySet()){
                ps.setObject(k,map.get(k));
            }
            return ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return -1;
    }
    //执行查询语句-返回单条数据  反射
    public static <T> T execuSingle(String sql,Class<T> clz){
        try {
            //预处理对象 防止SQL注入
            PreparedStatement ps=connection.prepareStatement(sql);
            ResultSet rs= ps.executeQuery();
            T obj=clz.newInstance();
            while (rs.next()){
               // clz.getFields();
                Field[] arr=clz.getDeclaredFields();
                for(Field f:arr){
                    f.setAccessible(true);//过滤访问权限
                    f.set(obj,rs.getObject(f.getName()));
                }
            }
            return obj;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
    //执行查询语句
    public static ResultSet execuSingle(String sql){
        try {
            //预处理对象 防止SQL注入
            PreparedStatement ps=connection.prepareStatement(sql);
            return ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
